package com.example.shopping.service;

import com.example.shopping.entity.Goods;
import com.example.shopping.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GoodsService {
    //调用mapper方法，拿到所有的商品数据
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private RedisService redisService;

    //返回所有的商品数据
    public List<Goods> selectAll() {
        return goodsMapper.selectAll();
    }

    //返回所有的最新商品
    public List<Goods> selectAllNew() {
        return goodsMapper.selectAllNew();
    }


    public List<Goods> findByPage(int page, int pageSize, String searchName, Integer categoryId) {



        boolean useCache = searchName == null || searchName.isBlank();
        useCache = useCache && (categoryId == null || categoryId == 0);
        //如果有搜索条件，就不使用缓存
        if (useCache) {
            List<?> cachedData = redisService.getGoodsPage(page);
            if (cachedData != null) {
                System.out.println("使用缓存：第" + page + "页数据");
                return (List<Goods>) cachedData;
            }
        }

        System.out.println("新建或更新缓存：第" + page + "页数据");

        // 从数据库分页查询
        int offset = (page - 1) * pageSize;
        List<Goods> goods = goodsMapper.selectPage(offset, pageSize, searchName, categoryId);
        System.out.println(goods);

        if ((searchName != null && searchName.isBlank()) && (categoryId == null || categoryId == 0)) {
            redisService.cacheGoodsPage(page, goods);
        }

        return goods;
    }


    public long count(String searchName) {
        return goodsMapper.count(searchName);
    }

    public List<Goods> selectAllHot() {
        return goodsMapper.selectAllHot();
    }

    public Integer countByCategoryId(int categoryId) {
        return goodsMapper.countByCategoryId(categoryId);
    }

    public Goods findById(int id) {
        return goodsMapper.findById(id);
    }

    public boolean insertGood(Goods good) {
        good.setStatus("Y");
        good.setSaleTime(new Date());
        System.out.println(good);
        return goodsMapper.insertGood(good) > 0;

    }
}
